/*
 * ------------------------------------------------------------------
 * Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 * ------------------------------------------------------------------
 *       Product:
 *   Module Name:
 *  Date Created: 2022/10/8
 *   Description:
 * ------------------------------------------------------------------
 * Modification History
 * DATE            Name           Description
 * ------------------------------------------------------------------
 * 2022/10/8    小谷 g2038          created
 * ------------------------------------------------------------------
 */
package com.gujh.java.jmx.client;


import com.gujh.java.jmx.karaf.BundleState;
import com.gujh.java.jmx.karaf.KarafConsts;

import javax.management.JMException;
import javax.management.ObjectName;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class KarafJmxClient implements Closeable {

    private final JmxClient jmxClient;

    public KarafJmxClient(String host, String port, String user, String auth) throws IOException {
        jmxClient = JmxClientBuilder
                .jmxServiceUrl(String.format(KarafConsts.SERVICE_URL_TEMPLATE, host, port))
                .addCredentials(user, auth)
                .build();
    }

    public static KarafJmxClient defaultKarafJmxClient() throws IOException {
        return new KarafJmxClient(KarafConsts.DEFAULT_HOST, KarafConsts.DEFAULT_PORT,
                KarafConsts.KARAF_USER, KarafConsts.KARAF_AUTH);
    }

    public BundleState getBundleState(String bundleName) throws JMException, IOException {
        if (null == bundleName) {
            return null;
        }
        ObjectName objectName = new ObjectName(KarafConsts.BUNDLE_OBJECT);
        List<Object> params = Collections.singletonList(bundleName);
        List<String> paramTypes = Collections.singletonList(String.class.getName());
        String state = jmxClient.invoke(objectName, KarafConsts.BUNDLE_GET_STATUS_OPERATION,
                params, paramTypes, String.class);
        return BundleState.convertState(state);
    }

    @Override
    public void close() throws IOException {
        if (Objects.nonNull(jmxClient)) {
            jmxClient.close();
        }
    }
}
